package com.governtalk.backend.service.impl;

import com.governtalk.backend.dto.user.UserProfileDto;
import com.governtalk.backend.entity.User;
import com.governtalk.backend.repository.UserRepository;
import com.governtalk.backend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    private static final String UPLOAD_DIR = "uploads/avatar/";
    
    @Override
    public UserProfileDto getCurrentUserProfile() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication != null ? authentication.getName() : null;
            
            System.out.println("Current authentication: " + authentication);
            System.out.println("Current username: " + username);
            
            // 如果没有认证信息或用户名为anonymousUser，返回admin用户
            if (username == null || "anonymousUser".equals(username)) {
                System.out.println("No valid authentication, using admin user");
                User user = userRepository.findByUsername("admin")
                        .orElseThrow(() -> new RuntimeException("Default user not found"));
                return convertToDto(user);
            }
            
            User user = userRepository.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("User not found: " + username));
            
            System.out.println("Found user: " + user.getUsername());
            return convertToDto(user);
        } catch (Exception e) {
            System.err.println("Error in getCurrentUserProfile: " + e.getMessage());
            e.printStackTrace();
            // 如果出现任何异常，返回admin用户
            User user = userRepository.findByUsername("admin")
                    .orElseThrow(() -> new RuntimeException("Default user not found"));
            return convertToDto(user);
        }
    }
    
    @Override
    public UserProfileDto updateUserProfile(UserProfileDto userProfileDto) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("User not found"));
        
        user.setNickname(userProfileDto.getNickname());
        user.setBio(userProfileDto.getBio());
        user.setAvatarUrl(userProfileDto.getAvatar());
        user.setUpdatedAt(LocalDateTime.now());
        
        User savedUser = userRepository.save(user);
        return convertToDto(savedUser);
    }
    
    @Override
    public void changePassword(String currentPassword, String newPassword) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("User not found"));
        
        // 验证当前密码（这里简化处理，实际项目中应该使用PasswordEncoder）
        if (!currentPassword.equals(user.getPassword())) {
            throw new RuntimeException("Current password is incorrect");
        }
        
        // 设置新密码（这里简化处理，实际项目中应该加密）
        user.setPassword(newPassword);
        user.setUpdatedAt(LocalDateTime.now());
        userRepository.save(user);
    }
    
    @Override
    public String uploadAvatar(byte[] fileBytes, String fileName) {
        try {
            String fileExtension = fileName.substring(fileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString() + fileExtension;
            Path filePath = Paths.get(UPLOAD_DIR + newFileName);
            
            Files.createDirectories(filePath.getParent());
            Files.write(filePath, fileBytes);
            
            return "/uploads/avatar/" + newFileName;
        } catch (IOException e) {
            throw new RuntimeException("Failed to upload avatar", e);
        }
    }
    
    @Override
    public Page<UserProfileDto> getUserList(String keyword, String role, String status, Pageable pageable) {
        // 这里需要根据实际需求实现搜索逻辑
        Page<User> users = userRepository.findAll(pageable);
        return users.map(this::convertToDto);
    }
    
    @Override
    public void updateUserStatus(Long userId, String status) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found"));
        
        if ("ACTIVE".equals(status)) {
            user.setIsEnabled(true);
            user.setIsLocked(false);
        } else if ("BANNED".equals(status)) {
            user.setIsEnabled(false);
            user.setIsLocked(true);
        }
        
        user.setUpdatedAt(LocalDateTime.now());
        userRepository.save(user);
    }
    
    @Override
    public void updateUserRole(Long userId, String role) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found"));
        
        user.getRoles().clear();
        user.getRoles().add(role);
        user.setUpdatedAt(LocalDateTime.now());
        userRepository.save(user);
    }
    
    @Override
    public User findById(Long id) {
        return userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("User not found"));
    }
    
    @Override
    public User findByUsername(String username) {
        return userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("User not found"));
    }
    
    private UserProfileDto convertToDto(User user) {
        return UserProfileDto.builder()
                .id(user.getId())
                .username(user.getUsername())
                .nickname(user.getNickname())
                .email(user.getEmail())
                .avatar(user.getAvatarUrl())
                .bio(user.getBio())
                .website(null) // 暂时为空
                .location(null) // 暂时为空
                .gender(null) // 暂时为空
                .birthday(null) // 暂时为空
                .role("USER") // 临时设置默认角色
                .status(user.getIsEnabled() ? "ACTIVE" : "INACTIVE")
                .isEnabled(user.getIsEnabled())
                .isLocked(user.getIsLocked())
                .lastLogin(null) // 暂时为空
                .createdAt(user.getCreatedAt())
                .updatedAt(user.getUpdatedAt())
                .build();
    }
}
